<template>

  <!--页面区域-->
  <div>
    <div class="page-view">

      <!--搜索条件表单-->
      <div class="table-operations">
        
        <a-space>
          <a-form ref="queryForm" :model="data.queryParam" layout="inline">  
            <a-form-item label="资源编码">  
              <a-input v-model:value="data.queryParam.code" placeholder="请输入资源编码" />  
            </a-form-item>  
            <a-form-item label="资源名称">  
              <a-input v-model:value="data.queryParam.name" placeholder="请输入资源名称" />  
            </a-form-item>  
            <a-button type="primary" @click="onSearch">搜索</a-button> 
            <a-button type="primary" @click="onReset">重置</a-button> 
          </a-form> 
        </a-space> 
      </div>

      <!--标签table区域-->
      <a-tabs  @tabClick="handleChangeTab">
        <a-tab-pane key="1">
          <template #tab>
            <span>
              <apple-outlined />
              <!--标签table的名称-->
              资源列表
            </span>
          </template>
          
            <!--标签区域中的table-->
            <!--菜单资源可以做成树形结构，按钮和功能就是列表展示-->
            
            <a-table size="middle" rowKey="id" :loading="data.loading" :columns="columns" :data-source="data.dataList"
              @change="getResourceList" :scroll="{ x: 'max-content' }" :row-selection="rowSelection" :pagination="pagination">
              <template #bodyCell="{ text, record, index, column }">
                <template v-if="column.key === 'type'">
                  <span>
                    <span v-if="text === 1">菜单</span>
                    <span v-if="text === 2">按钮</span>
                    <span v-if="text === 3">功能</span>
                  </span>
                </template>
                <template v-if="column.key === 'dataStatus'">
                  <span>
                    <span v-if="text === 1"><a-tag color="success">启用</a-tag></span>
                    <span v-if="text === 0"><a-tag color="error">禁用</a-tag></span>
                  </span>
                </template>
                <template v-if="column.key === 'operation'">
                  <span>
                    <a @click="handleEdit(record)">编辑</a>
                    <a-divider type="vertical" />
                    <a-popconfirm title="确定删除?" ok-text="是" cancel-text="否" @confirm="confirmDelete(record)">
                      <a href="#">删除</a>
                    </a-popconfirm>
                  </span>
                </template>
              </template>
            </a-table>

        </a-tab-pane>

        <a-tab-pane key="2">
          <template #tab>
            <span>
              <apple-outlined />
              <!--标签table的名称-->
              资源树
            </span>
          </template>
          
          <!--标签区域中的table-->
          <!--菜单资源可以做成树形结构，按钮和功能就是列表展示-->
          <a-tree
            checkable
            :tree-data="treeData.dataList"
          >
            <template #title="{ name, code}">
              <span>{{ name }}</span>
            </template>
          </a-tree>
           

        </a-tab-pane>

        <a-tab-pane key="3">
          <template #tab>
            <span>
              <apple-outlined />
              <!--标签table的名称-->
              资源树形Table
            </span>
          </template>
          
          <!--标签区域中的table-->
          <a-table :columns="columns" :data-source="treeData.dataList" :row-selection="rowSelection2" >
            <template #bodyCell="{ text, record, index, column }">
                <template v-if="column.key === 'type'">
                  <span>
                    <span v-if="text === 1">菜单</span>
                    <span v-if="text === 2">按钮</span>
                    <span v-if="text === 3">功能</span>
                  </span>
                </template>
                <template v-if="column.key === 'dataStatus'">
                  <span>
                    <span v-if="text === 1"><a-tag color="success">启用</a-tag></span>
                    <span v-if="text === 0"><a-tag color="error">禁用</a-tag></span>
                  </span>
                </template>
                <template v-if="column.key === 'operation'">
                  <span>
                    <a @click="handleEdit(record)">编辑</a>
                    <a-divider type="vertical" />
                    <a-popconfirm title="确定删除?" ok-text="是" cancel-text="否" @confirm="confirmDelete(record)">
                      <a href="#">删除</a>
                    </a-popconfirm>
                    <a-divider type="vertical" />
                    <a @click="handleAddChildren(record)">新增子级</a>
                  </span>
                </template>
              </template>
          </a-table>
           

        </a-tab-pane>

        <template #tabBarExtraContent class="tabs-operations">
          <a-button type="primary" @click="handleAdd">新增</a-button>
          <a-popconfirm title="确定删除?" ok-text="是" cancel-text="否" @confirm="handleBatchDelete">
            <a-button >批量删除</a-button>
          </a-popconfirm>
        </template>

      </a-tabs>
    </div>


    <!--弹窗区域-->
    <!--新增/编辑 资源的弹窗-->
    <div>
      <a-modal :visible="modal.visile" :forceRender="true" :title="modal.title" ok-text="确认" cancel-text="取消"
        @cancel="handleCancel" @ok="handleOk">
        <div>
          <a-form ref="myform" :label-col="{ style: { width: '80px' } }" :model="modal.form" :rules="modal.rules">
            <a-row :gutter="24">
              <a-col span="24">
                <a-form-item label="资源类型" name="code">
                    <a-select :disabled="modal.editFlag" placeholder="请选择" allowClear v-model:value="modal.form.type">
                      <template v-for="item in modal.typeData">
                        <a-select-option :value="item.id">{{ item.title }}</a-select-option>
                      </template>
                    </a-select>
                </a-form-item>
              </a-col>
              <a-col span="24">
                <a-form-item label="资源编码" name="code">
                  <a-input  :disabled="modal.editFlag" placeholder="请输入" v-model:value="modal.form.code"
                    allowClear />
                </a-form-item>
              </a-col>
              <a-col span="24">
                <a-form-item label="资源名称" name="name">
                 <a-input placeholder="请输入" v-model:value="modal.form.name" allowClear />
                </a-form-item>
              </a-col>
              <a-col span="24">
                <a-form-item label="资源路径" name="resUrl">
                 <a-input placeholder="请输入" v-model:value="modal.form.resUrl" allowClear />
                </a-form-item>
              </a-col>
              <a-col span="24">
                <a-form-item label="状态" name="dataStatus">
                  <a-switch checked-children="启" un-checked-children="禁" v-model:checked="modal.form.dataStatusChecked" />
                </a-form-item>
              </a-col>
              <a-col span="24">
                <a-form-item label="备注" name="remark">
                  <a-textarea
                    v-model:value="modal.form.remark"
                    placeholder="请输入"
                    :auto-size="{ minRows: 2, maxRows: 5 }"
                  />
                </a-form-item>
              </a-col>
            </a-row>
          </a-form>
        </div>
      </a-modal>
    </div>
  </div>
</template>

<script setup lang="ts">
import { FormInstance, message, TreeProps } from 'ant-design-vue';
import { queryListApi, queryMenuTreeDataApi, createApi, updateApi, deleteApi } from '/@/api/resource';
import { getFormatTime } from "/@/utils";
import { AppleOutlined, AndroidOutlined } from '@ant-design/icons-vue';
import { defineComponent, ref, watch } from 'vue';



const rowSelection2 = ref({
  onChange: (selectedRowKeys: (string | number)[], selectedRows: DataItem[]) => {
    console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
  },
  onSelect: (record: DataItem, selected: boolean, selectedRows: DataItem[]) => {
    console.log(record, selected, selectedRows);
  },
  onSelectAll: (selected: boolean, selectedRows: DataItem[], changeRows: DataItem[]) => {
    console.log(selected, selectedRows, changeRows);
  },
});


 // 控制页面列表显示的字段
const columns = reactive([
  {
    title: '序号',
    dataIndex: 'index',
    key: 'index',
    align: 'center',
  },
   {
    title: '资源类型',
    dataIndex: 'type',
    key: 'type',
    align: 'center',
  },
   {
    title: '资源编码',
    dataIndex: 'code',
    key: 'code',
    align: 'center',
  },
  {
    title: '资源名称',
    dataIndex: 'name',
    key: 'name',
    align: 'center',
  },
   {
    title: '资源路径',
    dataIndex: 'resUrl',
    key: 'resUrl',
    align: 'center',
  },
  {
    title: '备注',
    dataIndex: 'remark',
    key: 'remark',
    align: 'center',
  },
  {
    title: '状态',
    dataIndex: 'dataStatus',
    key: 'dataStatus',
    align: 'center',
    customRender: ({ text, record, index, column }) => (text === 1 ? '正常' : '禁用'),
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    key: 'createTime',
    align: 'center',
    customRender: ({ text }) => getFormatTime(text, true)
  },
  {
    title: '操作',
    dataIndex: 'action',
    key: 'operation',
    align: 'center',
    fixed: 'right',
    width: 180,
  },
]);



// 页面数据
const data = reactive({
  dataList: [],
  queryParam: {
    keyword: '',
    pageSize: 10,
    page: 1,
    total: 0,
    type: '',
    code: '',
    name: '',
  },
  loading: false,
  selectedRowKeys: [] as any[],
});
const pagination = computed(() => ({
  size: 'default',
  current: data.queryParam.page,
  pageSize: data.queryParam.pageSize,
  total: data.queryParam.total,
  onChange: (current) => (data.queryParam.page = current),
  showSizeChanger: false,
  showTotal: (total) => `共${total}条数据`,
}));

// 系统资源数据
const treeData = reactive({
  dataList: [],
});

// 弹窗数据源
const modal = reactive({
  visile: false,
  editFlag: false,
  title: '',
  typeData: [
    {
      id: 1,
      title: '菜单',
    },
    {
      id: 2,
      title: '按钮',
    },
    {
      id: 3,
      title: '功能',
    },
  ],
  form: {
    id: undefined,
    parentId: undefined,
    code: undefined,
    name: undefined,
    resUrl: undefined,
    dataStatus: undefined,
    remark: undefined,
    dataStatusChecked: true,
  },
  rules: {
    code: [{ required: true, message: '请输入', trigger: 'change' }],
    name: [{ required: false, message: '请输入', trigger: 'change' }],
    remark: [{ required: false, message: '请选择', trigger: 'change' }]
  },
});

// 新增或编辑的表单
const myform = ref<FormInstance>();

// 搜索的表单
const queryForm = ref<FormInstance>();

// 点击菜单第一次页面渲染
onMounted(() => {
  getResourceList();
});

// 列表查询
const getResourceList = () => {
  data.loading = true;
  console.log("搜索条件：");
  console.log(data.queryParam);
  queryListApi(data.queryParam)
    .then((res) => {
      data.loading = false;
      data.dataList = res.content.records;
      data.queryParam.total = res.content.total;
      data.dataList.forEach((item: any, index: any) => {
        item.index = index + 1;
      });
    })
    .catch((err) => {
      data.loading = false;
      console.log(err);
    });
};

// 树形结构的菜单列表查询
const getMenuTreeData = () => {
  data.loading = true;
  queryMenuTreeDataApi(data.queryParam)
    .then((res) => {
      treeData.dataList = res.content;
      treeData.dataList.forEach((item: any, index: any) => {
        item.index = index + 1;
      });
      console.log('getMenuTreeData 数据');
      console.log(res.content);
    })
    .catch((err) => {
      data.loading = false;
      console.log(err);
    });
};

// 搜索按钮调用列表查询接口
const onSearch = () => {
  getResourceList();
};

// 重置搜索条件
const onReset = () => {
  data.queryParam.code = '';
  data.queryParam.name = '';
  getResourceList();
};


const rowSelection = ref({
  onChange: (selectedRowKeys: (string | number)[], selectedRows: DataItem[]) => {
    console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
    data.selectedRowKeys = selectedRowKeys;
  },
});

// 新增的方法
const handleAdd = () => {
  resetModal();
  modal.visile = true;
  modal.editFlag = false;
  modal.title = '新增';
  // 重置
  for (const key in modal.form) {
    modal.form[key] = undefined;
  }
  modal.form.dataStatusChecked = true;
};

// 编辑的方法
const handleEdit = (record: any) => {
  resetModal();
  modal.visile = true;
  modal.editFlag = true;
  modal.title = '编辑';
  // 重置
  for (const key in modal.form) {
    modal.form[key] = undefined;
  }
  for (const key in record) {
    modal.form[key] = record[key];
  }
  if(modal.form.dataStatus === 1){
    modal.form.dataStatusChecked = true;
  }
};

// 删除的方法
const confirmDelete = (record: any) => {
  console.log('delete', record);
  deleteApi({ ids: record.id })
    .then((res) => {
      message.success('删除成功');
      getResourceList();
    })
    .catch((err) => {
      message.error(err.response.data.message || "操作失败")
    });
};

// 批量删除的方法
const handleBatchDelete = () => {
  console.log(data.selectedRowKeys);
  if (data.selectedRowKeys.length <= 0) {
    message.warn('请勾选删除项');
    return;
  }
  deleteApi({ ids: data.selectedRowKeys.join(',') })
    .then((res) => {
      message.success('删除成功');
      data.selectedRowKeys = [];
      getResourceList();
    })
    .catch((err) => {
      message.error(err.response.data.message || "操作失败")
    });
};

// 二次确认 点击ok的方法
const handleOk = () => {
  myform.value
    ?.validate()
    .then(() => {
      const formData = new FormData();
      if (modal.form.id) {
        formData.append('id', modal.form.id);
      }
      if (modal.form.parentId) {
        formData.append('parentId', modal.form.parentId);
      }
      if (modal.form.code) {
        formData.append('code', modal.form.code);
      }
      if (modal.form.name) {
        formData.append('name', modal.form.name);
      }
      if (modal.form.remark) {
        formData.append('remark', modal.form.remark);
      }
      if (modal.form.dataStatusChecked && modal.form.dataStatusChecked === true) {
        formData.append('dataStatus', 1);
      } else {
        formData.append('dataStatus', 0);
      }
      if (modal.form.resUrl) {
        formData.append('resUrl', modal.form.resUrl);
      }
      if (modal.form.type) {
        formData.append('type', modal.form.type);
      }
      if (modal.editFlag) {
        updateApi(formData)
          .then((res) => {
            message.success('修改成功');
            hideModal();
            getResourceList();
            getMenuTreeData();
          })
          .catch((err) => {
            console.log(err);
            message.error(err.response.data.message || "操作失败")
          });
      } else {
        createApi(formData)
          .then((res) => {
            message.success('添加成功');
            hideModal();
            getResourceList();
            getMenuTreeData();
          })
          .catch((err) => {
            console.log(err);
            message.error(err.response.data.message || "操作失败")
          });
      }
    })
    .catch((err) => {
      console.log('不能为空');
    });
};

// 二次确认点击取消的方法
const handleCancel = () => {
  hideModal();
};

// 恢复表单初始状态
const resetModal = () => {
  myform.value?.resetFields();
};

// 关闭弹窗
const hideModal = () => {
  modal.visile = false;
};


// 切换Tab标签页的回调方法
const handleChangeTab = (targetKey: string) => {
  if(targetKey === '2' || targetKey === '3'){
    getMenuTreeData();
  }else {
    getResourceList();
  }
}

//新增子级资源的方法,打开弹窗
const handleAddChildren = (record: any) => {
  resetModal();
  modal.visile = true;
  modal.editFlag = false;
  modal.title = '新增';
  // 重置
  for (const key in modal.form) {
    modal.form[key] = undefined;
  }
  modal.form.parentId = record.id;
  modal.form.dataStatusChecked = true;
};



</script>

<style scoped lang="less">
.page-view {
  min-height: 100%;
  background: #fff;
  padding: 24px;
  display: flex;
  flex-direction: column;
}

.table-operations {
  margin-bottom: 16px;
  text-align: right;
}

.table-operations>button {
  margin-right: 8px;
}


// 以下class名称是组件生成的，查看页面元素才知道
.ant-form> button {
  margin-right: 8px;
}

.ant-tabs-extra-content > button {
  margin-right: 8px;
}
</style>
